package Script;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextReader {
	
	/**
	 * Returns the entire script files content as a String.
	 * @throws FileNotFoundException 
	 * 
	 * @throws FileNotFoundException 
	 */
	public static String getText(File script, String charset) throws FileNotFoundException {
		StringBuilder text = new StringBuilder();
	    String newline = System.getProperty("line.separator");
	    Scanner scanner = new Scanner(script, charset);
	    String returnText;
	    String pointerRegex; 
		Pattern pattern;
		Matcher matcher;
		int dumpPosition = -1;
	   
	    try {
	    	while (scanner.hasNextLine()){
	    		text.append(scanner.nextLine() + newline);
	    	}
	    } finally{
	      scanner.close();
	    }
	    
	    /* 
	     * Check if there's a <BEGIN SCRIPT> in the text. Remove it, and
	     * all text prior to it.
	     */
	    pointerRegex = "<BEGIN SCRIPT>";
	    pattern = Pattern.compile(pointerRegex);
		matcher = pattern.matcher(text);

		
		/* 
		 * Get all matches. Note that this method will find the
		 * last instance of <BEGIN SCRIPT> if there are multiples.
		 */
		while (matcher.find()) {
			dumpPosition = matcher.end();
		}
		
		/* 
		 * Remove <BEGIN SCRIPT>, as well as the subsequent linebreak.
		 */
		if (dumpPosition > 0) {
			returnText = text.substring(dumpPosition + newline.length());
		} else {
			returnText = text.toString();
		}
	    
	    /* Remove last newline chars if any text was found. */
		if (returnText.length() >= newline.length()) {
			returnText = returnText.substring(0, returnText.length() - newline.length());
		}
		
	    return returnText;
	}
}
